package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.IterativeCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

public class Flink10_CEP_Pattern_Within {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从文件读取数据
        SingleOutputStreamOperator<WaterSensor> dataStream = env.readTextFile("input/sensor3.txt")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        return element.getTs() * 1000;
                                    }
                                })
                );

        //TODO 3.定义规则（模式） 匹配id为Sensor_1的数据
        Pattern<WaterSensor, WaterSensor> pattern =
                        Pattern.<WaterSensor>begin("start")
                                //迭代条件
                                .where(new IterativeCondition<WaterSensor>() {
                                    @Override
                                    public boolean filter(WaterSensor value, Context<WaterSensor> ctx) throws Exception {
                                        return "sensor_1".equals(value.getId());
                                    }
                                })
                                //严格连续
                                .next("end")
                                .where(new IterativeCondition<WaterSensor>() {
                                    @Override
                                    public boolean filter(WaterSensor value, Context<WaterSensor> ctx) throws Exception {
                                        return "sensor_2".equals(value.getId());
                                    }
                                })
                //超时数据
                .within(Time.seconds(3));


        //TODO 4.将模式作用于流上
        PatternStream<WaterSensor> patternStream = CEP.pattern(dataStream, pattern);

        //TODO 5.获取匹配到的数据
        SingleOutputStreamOperator<String> result = patternStream.select(new OutputTag<String>("timeout") {
                                                                         }, new PatternTimeoutFunction<WaterSensor, String>() {
                                                                             @Override
                                                                             public String timeout(Map<String, List<WaterSensor>> pattern, long timeoutTimestamp) throws Exception {
                                                                                 return pattern.toString();
                                                                             }
                                                                         },
                new PatternSelectFunction<WaterSensor, String>() {
                    @Override
                    public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                        return pattern.toString();
                    }
                }
        );


        result.print("正常匹配到的");

        result.getSideOutput(new OutputTag<String>("timeout") {
        }).print("超时数据");

        env.execute();
    }
}
